package com.blacktech.dbu.auth.repository;

import com.blacktech.dbu.auth.entity.DbuUserProduct;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

/**
 * 用户产品权限数据访问层
 *
 * @author Yanyunsong
 */
@Repository
public interface UserProductRepository extends JpaRepository<DbuUserProduct, Long> {

    /**
     * 根据用户ID查找产品权限
     */
    List<DbuUserProduct> findByUserId(Long userId);

    /**
     * 根据产品ID查找用户权限
     */
    List<DbuUserProduct> findByProductId(Long productId);

    /**
     * 根据用户ID和产品ID查找权限
     */
    Optional<DbuUserProduct> findByUserIdAndProductId(Long userId, Long productId);

    /**
     * 检查用户是否有特定或更高权限
     */
    @Query("SELECT COUNT(up) > 0 FROM DbuUserProduct up WHERE up.user.id = :userId AND up.product.id = :productId AND up.permissionLevel <= :permissionLevel")
    boolean hasHigherPermission(@Param("userId") Long userId, @Param("productId") Long productId, @Param("permissionLevel") int permissionLevel);

    /**
     * 查找用户有权限的所有产品
     */
    @Query("SELECT up FROM DbuUserProduct up WHERE up.user.id = :userId ORDER BY up.permissionLevel ASC")
    List<DbuUserProduct> findUserPermissions(@Param("userId") Long userId);

    /**
     * 查找产品的所有用户权限
     */
    @Query("SELECT up FROM DbuUserProduct up WHERE up.product.id = :productId ORDER BY up.permissionLevel ASC")
    List<DbuUserProduct> findProductPermissions(@Param("productId") Long productId);

    /**
     * 分页查询用户产品权限
     */
    @Query("SELECT up FROM DbuUserProduct up WHERE " +
            "(:userId IS NULL OR up.user.id = :userId) AND " +
            "(:productId IS NULL OR up.product.id = :productId) AND " +
            "(:permissionLevel IS NULL OR up.permissionLevel = :permissionLevel)")
    Page<DbuUserProduct> findByConditions(@Param("userId") Long userId,
                                          @Param("productId") Long productId,
                                          @Param("permissionLevel") Integer permissionLevel,
                                          Pageable pageable);

    /**
     * 根据产品ID删除所有用户权限记录
     */
    void deleteByProductId(Long productId);

}